<template>
	<view class="content">
		<SideEdge :Dataindex='2'></SideEdge>
		<view class="right">
			<search></search>
			<!-- 题目概况 -->
			<view class="subject" v-if="list.length > 0 && !Full" :class="{fullSubject: Full}">
				<!-- <view class="oneline">
					<view class="leftBox">
						<text>求解问题</text>
						<view class="backdrop"></view>
					</view>
				</view> -->
				<view class="twoline">
					<text class="leftText">{{index + 1}}、{{list[index].title}}</text>
					<image @click="onPreviewImage"
						style="width: 100px;height: 100px;min-height: 100px;min-width: 100px;" v-if="list[index].image"
						:src="list[index].image" mode=""></image>
				</view>
			</view>
			<view class="answer" v-if="list.length > 0">
				<view class="title">
					<text>填写问题</text>
					<view class="backdrop"></view>
				</view>
				<view class="line"></view>
				<!-- 单选题 -->
				<up-radio-group v-if="list[index].type == 1 " v-model="list[index].value" placement="column"
					@change="groupChange">
					<up-radio :customStyle="{marginBottom: '8px'}" v-for="(item, index) in list[index].option"
						:key="index" :label="item.name" :name="item.value" @change="radioChange">
					</up-radio>
				</up-radio-group>
				<!-- 简答题或者填空题 -->
				<view class="Controls" v-if=" list[index].type == 4 || list[index].type == 3">
					<view class="ControlsItem" v-if="!eraserEnabled" @click="toggleEraser"
						style="background-color: #FFFFFF;">
						<image src="https://img.wilmer.com.cn/admin/2024/6-21/%E6%A9%A1%E7%9A%AE%E6%93%A6%281%29.png"
							mode="">
						</image>
					</view>
					<view class="ControlsItem" v-if="eraserEnabled" @click="toggleEraser">
						<image src="https://img.wilmer.com.cn/admin/2024/6-21/%E6%A9%A1%E7%9A%AE%E6%93%A6.png" mode="">
						</image>
					</view>
					<view class="buttonItem" @click="FullScreen" v-if="!Full">
						<image src="https://img.wilmer.com.cn/admin/2024/6-12/%E5%85%A8%E5%B1%8F.png" mode="">
						</image>
					</view>
					<view class="ControlsItem" @click="FullScreen" v-if="Full">
						<image src="https://img.wilmer.com.cn/admin/2024/6-20/%E5%85%A8%E5%B1%8F%20%281%29.png" mode="">
						</image>
					</view>
					<view class="btn" hover-class="checkActive" hover-stay-time='20'
						v-if="index < list.length -1 && Full" @click="onnext()">下一题</view>
				</view>
				<view style="border: 1px solid #000;" v-show=" list[index].type == 4 || list[index].type == 3">
					<canvas canvas-id="handwriting" style="width: 100%;" :style="{height:`${canvasHeight}px`}"
						@touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd"></canvas>
				</view>
				<!-- <up-textarea v-if="list[index].type == 3 " v-model="list[index].value" placeholder="备注" height='300'
					border='none'></up-textarea> -->
			</view>
			<view class="btnBox" v-if="!Full">
				<view class="btn" hover-class="checkActive" hover-stay-time='20' @click="onPrevious()">上一题</view>
				<view class="btn" hover-class="checkActive" hover-stay-time='20' v-if="index < list.length -1 "
					@click="onnext()">下一题</view>
				<view class="btn" hover-class="checkActive" hover-stay-time='20' v-if="index == list.length -1 "
					@click="onSubmit()">提交</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		Question,
		submitQuestion,
		identifyText
	} from '@/common/api/subject.js'
	import {
		getSignedUrl
	} from '@/common/api/user.js'
	export default {
		data() {
			return {
				Full: false, // 是否正在绘画
				isDrawing: false, // 是否正在绘画
				ctx: null, // Canvas 上下文对象
				lastX: 0, // 上一次触摸的 X 坐标
				lastY: 0, // 上一次触摸的 Y 坐标
				eraserEnabled: false, // 橡皮擦模式是否启用
				canvasWidth: 0, // 画布宽度
				canvasHeight: 300, // 画布高度
				initialTouch: [], // 初始触摸点
				translateX: 0, // 当前平移 X 轴
				translateY: 0, // 当前平移 Y 轴
				initialTranslateX: 0, // 初始平移 X 轴
				initialTranslateY: 0, // 初始平移 Y 轴
				savedImage: "",


				key: "",
				policy: "",
				success_action_status: "",
				host: "",
				Signature: "",
				OSSAccessKeyId: "",

				list: [],
				index: 0,
			};
		},
		onReady() {
			this.ctx = uni.createCanvasContext('handwriting');
			const res = uni.getSystemInfoSync();
			this.canvasWidth = res.windowWidth;
			// this.canvasHeight = res.windowHeight;
			// 将画布的原点由左上角移动到中心点
			// this.ctx.translate(this.canvasWidth / 2, this.canvasHeight / 2);
		},
		onLoad(options) {
			getSignedUrl({
				route: "image"
			}).then(res => {
				this.key = res.data.key
				this.policy = res.data.policy
				this.success_action_status = res.data.success_action_status
				this.host = res.data.host
				this.Signature = res.data.Signature
				this.OSSAccessKeyId = res.data.OSSAccessKeyId
			})


			Question({
				subject_id: options.subject_id,
				class: options.class,
				joint: options.joint
			}).then(res => {
				let arr = []
				for (let i = 0; i < res.data.length; i++) {
					let item = res.data[i]
					if (item.type == 1 || item.type == 2) {
						arr.push({
							title: item.topic,
							image: item.image,
							value: "",
							option: [{
								name: 'A、' + item.option_a,
								value: '1'
							}, {
								name: 'B、' + item.option_b,
								value: '2'
							}, {
								name: 'C、' + item.option_c,
								value: '3'
							}, {
								name: 'D、' + item.option_d,
								value: '4'
							}],
							type: item.type,
							id: item.id
						})
					} else if (item.type == 3 || item.type == 4) {
						arr.push({
							image: item.image,
							title: item.topic,
							value: "",
							type: item.type,
							id: item.id
						})
					}
				}
				this.list = arr
			})
		},
		methods: {
			onPreviewImage() {
				var imgArr = [];
				imgArr.push(this.list[this.index].image);
				//预览图片
				uni.previewImage({
					urls: imgArr,
					current: imgArr[0]
				});
			},
			onnext() {
				let that = this
				if (this.list[this.index].type == 4 || this.list[this.index].type == 3) {
					// 处理 canvas、导出画布内容为图片
					uni.canvasToTempFilePath({
						canvasId: 'handwriting',
						success(res) {
							let keyone = that.key + new Date().getTime() + Math.floor(Math.random() * 150) +
								'.png'
							uni.uploadFile({
								url: that.host, //输入你的bucketname.endpoint
								filePath: res.tempFilePath,
								name: 'file',
								formData: {
									key: keyone,
									policy: that.policy, // 输入你获取的的policy
									OSSAccessKeyId: that.OSSAccessKeyId, // 输入你的AccessKeyId
									success_action_status: that
										.success_action_status, // 让服务端返回200,不然，默认会返回204
									signature: that.Signature, // 输入你获取的的signature
								},
								success: (res) => {
									identifyText({
										image: that.host + '/' + keyone
									}).then(res1 => {
										that.clearCanvas()
										that.canvasHeight = 300
										that.Full = false
										that.index += 1
										for (let i = 0; i < res1.data.length; i++) {
											that.list[that.index].value += res1.data[i]
												.words
										}
									})
								},
								fail: (err) => {
									console.log(err);
								}
							})
						},
						fail(err) {
							console.error('Failed to export canvas:', err);
						}
					});
				} else {
					if (this.list[this.index].value == '' && this.list.length - 1 > this.index) {
						uni.showToast({
							title: "请先回答当前问题",
							icon: 'none'
						});
					} else {
						this.index += 1
					}
				}
			},

			onPrevious() {
				if (this.index >= 1) {
					this.index -= 1
				}
			},

			onSubmit() {
				let answer_result = []
				let that = this
				if (this.list[this.list.length - 1].type == 3 || this.list[this.list.length - 1].type == 4) {
					uni.canvasToTempFilePath({
						canvasId: 'handwriting',
						success(res) {
							let keyone = that.key + new Date().getTime() + Math.floor(Math.random() * 150) +
								'.png'
							uni.uploadFile({
								url: that.host, //输入你的bucketname.endpoint
								filePath: res.tempFilePath,
								name: 'file',
								formData: {
									key: keyone,
									policy: that.policy, // 输入你获取的的policy
									OSSAccessKeyId: that.OSSAccessKeyId, // 输入你的AccessKeyId
									success_action_status: that
										.success_action_status, // 让服务端返回200,不然，默认会返回204
									signature: that.Signature, // 输入你获取的的signature
								},
								success: (res) => {
									identifyText({
										image: that.host + '/' + keyone
									}).then(res1 => {

										for (let j = 0; j < res1.data.length; j++) {
											that.list[that.index].value += res1.data[j]
												.words
										}

										for (let i = 0; i < that.list.length; i++) {
											let item = that.list[i]

											answer_result.push({
												question_id: item.id,
												answer: item.value,
											})

										}

										submitQuestion({
											answer_result
										}).then(res => {
											uni.switchTab({
												url: '/pages/index/subject'
											})
											return false
										})
									})
								},
								fail: (err) => {
									console.log(err);
								}
							})
						},
						fail(err) {
							console.error('Failed to export canvas:', err);
						}
					});
				} else {
					for (let i = 0; i < this.list.length; i++) {
						let item = this.list[i]

						if (item.value == '') {
							uni.showToast({
								title: '请完成所有题目后再提交',
								icon: 'none'
							})
							return false
						}

						answer_result.push({
							question_id: item.id,
							answer: item.value,
						})

					}

					submitQuestion({
						answer_result
					}).then(res => {
						if (res.code == 1) {
							uni.switchTab({
								url: '/pages/index/subject'
							})
						}
					})
				}
			},
			groupChange(n) {
				console.log('groupChange', n);
			},
			radioChange(n) {
				console.log('radioChange', n);
			},


			startDrawing(e) {
				if (Object.keys(e.touches).length === 1) {
					this.isDrawing = true;
					this.lastX = e.touches[0].x;
					this.lastY = e.touches[0].y;
				}
			},
			// 绘画过程
			draw(e) {
				if (!this.isDrawing) return;
				if (Object.keys(e.touches).length !== 1) return;
				const x = e.touches[0].x;
				const y = e.touches[0].y;
				// 设置线条宽度和颜色
				this.ctx.setLineWidth(this.eraserEnabled ? 60 : 2);
				this.ctx.setStrokeStyle(this.eraserEnabled ? '#FFFFFF' : '#000000');
				this.ctx.beginPath();
				this.ctx.moveTo(this.lastX, this.lastY);
				this.ctx.lineTo(x, y);
				this.ctx.stroke();
				this.ctx.draw(true);
				// 更新最后一次触摸的坐标
				this.lastX = x;
				this.lastY = y;

			},
			// 停止绘画
			stopDrawing() {
				this.isDrawing = false;
			},
			// 清除画布
			clearCanvas() {
				this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
				this.ctx.draw();
			},
			// 切换橡皮擦模式
			toggleEraser() {
				this.eraserEnabled = !this.eraserEnabled;
			},
			// 全屏功能 
			FullScreen() {
				this.Full = !this.Full
				if (this.Full) {
					this.canvasHeight = 640
				} else {
					this.canvasHeight = 300
				}
			},
			/** 
			 * onTouchStart 绘画开始
			 * onTouchMove 绘画移动中
			 * onTouchEnd 绘画结束
			 */
			onTouchStart(e) {
				if (Object.keys(e.touches).length === 1) {
					this.startDrawing(e);
				} else if (Object.keys(e.touches).length === 2) {
					this.initialTouch = e.touches.map(touch => ({
						x: touch.x,
						y: touch.y
					}));
					this.initialTranslateX = this.translateX;
					this.initialTranslateY = this.translateY;
					this.saveCurrentCanvas()
				}
			},
			onTouchMove(e) {
				if (Object.keys(e.touches).length === 1) {
					this.draw(e);
				} else if (Object.keys(e.touches).length === 2) {
					const dx = (e.touches[0].x + e.touches[1].x) / 2 - (this.initialTouch[0].x + this.initialTouch[1].x) /
						2;
					const dy = (e.touches[0].y + e.touches[1].y) / 2 - (this.initialTouch[0].y + this.initialTouch[1].y) /
						2;
					this.translateX = this.initialTranslateX + dx;
					this.translateY = this.initialTranslateY + dy;
					this.applyTranslation();
				}
			},
			onTouchEnd() {
				this.stopDrawing();
			},
			saveCurrentCanvas() {
				const that = this;
				uni.canvasToTempFilePath({
					canvasId: 'handwriting',
					success(res) {
						that.savedImage = res.tempFilePath;
					},
					fail(err) {
						console.error('Failed to save current canvas:', err);
					},
				});
			},
			// 应用平移
			applyTranslation() {
				if (!this.savedImage) return;
				const that = this;
				uni.getImageInfo({
					src: this.savedImage,
					success(imgInfo) {
						console.log(imgInfo.width, imgInfo.height, 'shuju001')
						that.ctx.clearRect(0, 0, that.canvasWidth, that.canvasHeight);
						that.ctx.save();
						that.ctx.translate(that.translateX, that.translateY);
						that.ctx.drawImage(that.savedImage, 0, 0, imgInfo.width / 2, imgInfo.height / 2);
						that.ctx.restore();
						that.ctx.draw();
					},
					fail(err) {
						console.error('Failed to get image info:', err);
					},
				});
			}
		},
	};
</script>

<style>
	page {
		width: 100%;
		height: auto;
		background: #F7F7F7;
		overflow-x: hidden;
	}
</style>

<style lang="scss" scoped>
	::v-deep .u-radio {
		margin-top: 20px;
		font-size: 20px;
		overflow: visible !important;
	}

	::v-deep .u-radio__icon-wrap {
		transform: scale(1.5) !important;
	}

	::v-deep .u-radio__text {
		margin-left: 24px;
		font-family: PingFangSC, PingFang SC;
		font-weight: 600 !important;
		font-size: 32 * 0.8px !important;
		color: #040404 !important;
		line-height: 1 !important;
	}

	.content {
		width: 100vw;
		height: 100vh;
		display: flex;
		align-items: center;
		position: relative;
	}

	.content .right {
		width: calc(100vw - 300px);
		height: 100vh;
		overflow: overlay;
	}

	.content .right .subject {
		max-height: 170px;
		overflow: auto;
		background: #FFFFFF;
		border-radius: 20px;
		margin: 0 16px;
		padding: 20px 0;
		box-sizing: border-box;
		// display: flex;
		// flex-direction: column;
		// justify-content: center;

		.oneline {
			display: flex;
			position: relative;
			align-items: center;
			justify-content: space-between;

			.leftBox {
				margin-left: 40px;

				text {
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					font-size: 24px;
					color: #040404;
					line-height: 34px;
					position: relative;
					z-index: 999;
				}

				.backdrop {
					width: 100%;
					position: relative;
					bottom: 15px;
					height: 13px;
					background: #2283E2;
				}
			}
		}

		.twoline {
			margin-top: 10px;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.leftText {
				margin-left: 40px;
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 32 * 0.8px;
				color: #040404;
				line-height: 45px;
			}
		}
	}

	.content .right .fullSubject {
		transition: all 1s;
		height: 0 !important;
		padding: 0 !important;
	}

	.content .right .answer {
		min-height: 678 * 0.7px;
		background: #FFFFFF;
		border-radius: 20px;
		margin: 20px 16px 0;
		padding-top: 20px;
		box-sizing: border-box;

		.title {
			margin-left: 40px;

			text {
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 24px;
				color: #040404;
				line-height: 34px;
				position: relative;
				z-index: 999;
			}

			.backdrop {
				width: 96px;
				position: relative;
				bottom: 15px;
				height: 13px;
				background: #2283E2;
			}
		}

		.line {
			height: 1px;
			background: #B2B1AF;
			opacity: 0.3;
			margin: 0 40px;
		}

		.Controls {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-right: 40px;
			padding: 20px;
			box-sizing: border-box;

			.ControlsItem {
				width: 30px;
				height: 30px;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: #040404;
				margin: 0 10px;

				image {
					width: 20px;
					height: 20px;
				}
			}

			.buttonItem {
				width: 30px;
				height: 30px;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0 10px;

				image {
					width: 20px;
					height: 20px;
				}
			}

			.btn {
				padding: 0 20px;
				height: 30px;
				background: #040404;
				border-radius: 12px;

				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 16px;
				color: #FFFFFF;

				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	::v-deep .u-radio-group {
		margin-left: 40px;
		margin-top: 40px;
	}

	::v-deep .u-textarea {
		margin: 20px 40px 0;
		background: #F8F8F8;
		border-radius: 18px;
	}

	.btnBox {
		margin: 20px 16px 0;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.btn {
			width: 200px;
			height: 68px;
			background: #040404;
			border-radius: 12px;

			font-family: PingFangSC, PingFang SC;
			font-weight: 600;
			font-size: 24px;
			color: #FFFFFF;
			line-height: 26px;

			display: flex;
			align-items: center;
			justify-content: center;
		}

		.btn:nth-child(1) {
			border: 1px solid #040404;
			color: #040404;
			background: transparent;
		}
	}
</style>